/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.esgi.dns.server;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;

/**
 *
 * @author amine
 */
public class Server {
    ServerSocket _socket;
    String hostname;
    int port;
    public Server(String hostName,int port){
        this.hostname=hostName;
        this.port = port;
    }
     public void start() {
        System.out.println("Starting server " + hostname + ":" + port);
        try {
            _socket = new ServerSocket();
            _socket.bind(new InetSocketAddress(hostname, port));
            Socket client;
            while(null!=(client=_socket.accept()))
                _proceedProtocol(client);
            
        } catch (Exception e) {
            e.printStackTrace();
            //System.exit(1);
        }
     }
     private void _proceedProtocol(Socket client) throws Exception{
         System.out.println("read socket ...");
        byte[] resultBuff = new byte[0];
        byte[] buff = new byte[1024];
        int k = -1;
        while((k = client.getInputStream().read(buff, 0, buff.length)) > -1) {
            byte[] tbuff = new byte[resultBuff.length + k];
            System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); 
            System.arraycopy(buff, 0, tbuff, resultBuff.length, k);
            resultBuff = tbuff;
        }
      ByteBuffer bb = ByteBuffer.allocate(resultBuff.length);
      bb.put(resultBuff);
       /*  Message message = null;
         if(0 < resultBuff.length){
             System.out.println("prepare message ...");
            message = new Message(resultBuff);
             System.out.println("send response socket ...");
             //client.getOutputStream().write(message.toSend());       
         }
        client.close();*/
    }
     public static void main(String[] args) throws Exception {
        Server server = new Server("localhost", 6789);
        server.start();
    }
}
